import mitt from "mitt";

export enum MessageType {
    HEART = "HEART",
    PERSON = "PERSON",
    ROOM = "ROOM",
    CREATE_ROOM = "CREATE_ROOM",
    JOIN_ROOM = "JOIN_ROOM",
    EXIT_ROOM = "EXIT_ROOM",
    NOTICE = "NOTICE",
    MEMBER_JOIN = "MEMBER_JOIN",
    MEMBER_EXIT = "MEMBER_EXIT",
    MEMBER_LIST = "MEMBER_LIST"
}

export interface Message {
  messageType: MessageType,
  senderId: string,
  senderName: string,
  targetId: string,
  content: any,
  time?: string,
  code?: number
}

export const eventBus = mitt();
export let socket: WebSocket | null;
let intervalId = 0
export const createWebSocket = (id: string) => {
  if (socket) {
    return socket;
  }

  socket = new WebSocket(`/jiancai/ws?id=${id}`);
  
  // 接收消息处理
  socket.onmessage = function (event) {
    eventBus.emit("onmessage", event);
  };

  socket.onopen = (event) => {
    eventBus.emit("onopen", event);

    clearInterval(intervalId)
    intervalId = setInterval(() => {
        
        sendMessage({
            messageType: MessageType.HEART,
            senderId: id,
            senderName: id + '-name',
            targetId: '',
            content: 'ping'
        })
    }, 30000)
  };

  socket.onclose = (event) => {
    eventBus.emit("onclose", event);

    setTimeout(() => {
      // 断开重连
      socket = null;
      createWebSocket(id);
    }, 30000);
  };

  return socket;
};

// 发送消息
export function sendMessage(obj: Message) {
    if(!socket){
      console.log("socket 还没有创建")
      return
    }
    socket.send(JSON.stringify(obj));
}